package api

import (
	"github.com/gin-gonic/gin"
	"vtrip/global"
	"vtrip/internal/service"
	"vtrip/pkg/app"
	"vtrip/pkg/errcode"
)

type User struct{}

func NewUser() User {
	return User{}
}

// WChatLogin
// @Summary 微信登录
// @Produce json
// @Param nick_name body string true "昵称"
// @Param w_chat_id body string true "微信 id"
// @Param avatar_url body string true "用户头像"
// @Router /login/wchat [post]
// @Success 200 {object} nil "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
func (u User) WChatLogin(c *gin.Context) {
	// 参数校验
	param := service.WChatLoginRequest{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errResponse := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errResponse)
	}

	// 获取用户 id
	svc := service.New(c.Request.Context())
	userId, err := svc.WChatLogin(&param)
	if err != nil {
		global.Logger.Errorf("svc.WChatLogin err: %v", err)
		response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
		return
	}

	// 生成 Token
	token, err := app.GenerateToken(userId)
	if err != nil {
		global.Logger.Errorf("app.GenerateToken err: %v", err)
		response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
		return
	}

	response.ToSuccessResponse(gin.H{
		"token": token,
	})
}
